/*
 * @Descripttion: 二次封装axios
 * @version:
 * @Author: lhl
 * @Date: 2024-09-01 21:53:02
 * @LastEditors: lhl
 * @LastEditTime: 2024-09-10 10:56:31
 */

import axios, { AxiosInstance, InternalAxiosRequestConfig } from 'axios';
import { showLoadingToast, closeToast, showFailToast } from 'vant';

// 自定义请求配置类型
export interface CustomAxiosRequestConfig extends InternalAxiosRequestConfig {
  showLoading?: boolean; // 是否显示Loading
  showToast?: boolean; // 是否显示Toast
}

// 创建axios实例
const service: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_URL, // 设置API前缀
  timeout: 10000, // 请求超时时间 10s
  headers: { 'Content-Type': 'application/json;charset=utf-8' }
});

// 请求拦截器
service.interceptors.request.use(
  (config: CustomAxiosRequestConfig) => {
    // 拼接token
    const token = localStorage.getItem('token');
    if (token) {
      config.headers['x-access-token'] = `${token}`;
    }
    if (config.showLoading !== false) {
      // 自定义Loading
      showLoadingToast({
        message: '加载中...',
        forbidClick: true,
        duration: 0 // 持续显示，直到请求结束
      });
    }
    return config;
  },
  (error) => {
    closeToast(); // 清除Loading
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    console.log(response, 'response');
    closeToast(); // 清除Loading
    const config = response.config as CustomAxiosRequestConfig | any;
    const { code, message, object } = response.data || {};
    if (config.showToast !== false) {
      // 自定义Toast
      if (code !== 200) {
        showFailToast(message || 'Error');
      } else {
        return object;
      }
    }
    return response.data;
  },
  (error) => {
    closeToast(); // 清除Loading
    showFailToast(error.message || 'Error');
    // 网络连接失败
    if (!window.navigator.onLine) {
      showFailToast(error.message || '网络出错，请检查网络连接');
    }
    return Promise.reject(error);
  }
);

export default service;
